package com.example.youzhengyang

import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.room.Room
import com.example.youzhengyang.databinding.FragmentWordListBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.launch

class WordListFragment : Fragment() {
    private var _binding: FragmentWordListBinding? = null
    private val binding get() = _binding!!
    private lateinit var db: WordDatabase
    private lateinit var adapter: WordAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentWordListBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        db = Room.databaseBuilder(
            requireContext(),
            WordDatabase::class.java,
            "word_database"
        ).build()

        adapter = WordAdapter { word ->
            showDeleteDialog(word)
        }

        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = this@WordListFragment.adapter
        }

        binding.fab.setOnClickListener {
            findNavController().navigate(R.id.action_wordListFragment_to_addWordFragment)
        }

        viewLifecycleOwner.lifecycleScope.launch {
            db.wordDao().getAllWords().collect { words ->
                adapter.submitList(words)
            }
        }
    }

    private fun showDeleteDialog(word: Word) {
        MaterialAlertDialogBuilder(requireContext())
            .setTitle("删除单词")
            .setMessage("确定要删除这个单词吗？")
            .setPositiveButton("确定") { _, _ ->
                viewLifecycleOwner.lifecycleScope.launch {
                    db.wordDao().delete(word)
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 